package com.pshdhx.aiagent.app;

import com.alibaba.cloud.ai.advisor.DocumentRetrievalAdvisor;
import com.pshdhx.aiagent.advisor.MyLoggerAdvisor;
import com.pshdhx.aiagent.chatMemory.ChatMemoryByYu;
import com.pshdhx.aiagent.chatMemory.ChatMemoryByYu2;
import com.pshdhx.aiagent.chatMemory.SaveChatBySerializable;
import com.pshdhx.aiagent.rag.LoveAppContextQueryAugmentFactory;
import com.pshdhx.aiagent.rag.LoveAppRagCloudConfig;
import com.pshdhx.aiagent.rag.LoveAppRagCustomAdvisorFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @Author pansd
 * @Date 2025-06-23 14:22
 * @Des
 */

@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMTP = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。\" +\n" +
            "            \"围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；\" +\n" +
            "            \"恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。\" +\n" +
            "            \"引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    /**
     * 初始化ai客户端
     *
     * @param dashScopeChatModel
     */
    public LoveApp(ChatModel dashScopeChatModel) {
        //初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
//        ChatMemory chatMemory = new ChatMemoryByYu();
//        String fileDir = System.getProperty("user.dir") + "/chatMemory";
//        ChatMemory chatMemory = new ChatMemoryByYu2(fileDir);
        ChatMemory chatMemory = new SaveChatBySerializable();
        //初始化对话客户端
        chatClient = ChatClient.builder(dashScopeChatModel)
                .defaultSystem(SYSTEM_PROMTP)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
//                        new MyLoggerAdvisor()
                )
                .build();
    }

    /**
     * 支持ai基础对话（多轮）
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public Flux<String> doChatByStream(String message, String chatId) {
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }


    /**
     * //        //官方文档API
     * //        String officalContent = chatClient
     * //                .prompt()
     * //                .user(message)
     * //                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
     * //                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
     * //                .call()
     * //                .content();
     * //        log.info("officalContent: {}", officalContent);
     */

    record LoveReport(String title, List<String> suggestions) {

    }

    /**
     * 以指定结构，让AI大模型进行程序化输出
     *
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", loveReport);
        return loveReport;
    }


    @Resource
    private VectorStore loveAppVectorStore;

    /**
     * 基于内存向量数据 进行RAG知识库搜索
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用知识库问答
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //处理空回答，以特定内容回答
                //创建查询顾问，设置过滤条件
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore, "单身"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    @Resource
    private Advisor dashScopeRagCloudAdvisor;

    /**
     * 基于云知识库 进行RAG知识库搜索
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRagCloud(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
//                .advisors(new MyLoggerAdvisor())
                // 应用知识库问答，基于云知识库
                .advisors(dashScopeRagCloudAdvisor)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    @Resource
    private ToolCallback[] allTools;

    /**
     * spring ai 加载并根据语义，调用自定义工具
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithMyTools(String message, String chatId) {
        ChatClient.CallResponseSpec call = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(allTools)
                .call();
        ChatResponse chatResponse = call.chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

}
